/**
 * 
 */
package com.xcn.runtime;

import java.io.*;

import net.sf.json.*;

import com.xcn.exception.*;

/**
 * @author changmin
 *
 */
public class RuntimeExe
{
	
	/**
	 * 
	 */
	public RuntimeExe( )
	{
	}

	public static String getRuntime( String command ) throws XCNException
	{
		System.out.println ( "COMMAND : " + command );
		
		if ( command == null )
			throw new XCNException ( "command is not null" );
		
		StringBuffer _sb = new StringBuffer ( );
		Runtime runtime = null;
		Process process = null;
		BufferedReader br = null;
		try
		{
			runtime = Runtime.getRuntime ( );
			process = runtime.exec ( command );
			br = new BufferedReader ( new InputStreamReader ( process.getInputStream ( ) ) );
			String szLine;
			while ( (szLine = br.readLine ( )) != null )
			{
				_sb.append ( szLine ).append ( "\n" );
			}
		}
		catch ( Exception e )
		{
			e.printStackTrace ( );
		}
		finally
		{
			try { if ( process != null ) process.waitFor ( ); } catch ( Exception e ) { e.printStackTrace ( ); }
			try { if ( process != null ) process.destroy ( ); } catch ( Exception e ) { e.printStackTrace ( ); }
			try { if ( br != null ) br.close ( ); } catch ( Exception e ) { e.printStackTrace ( ); }
		}
		return _sb.toString ( );
	}
	
	/**
	 * @param args
	 * @throws InterruptedException 
	 * @throws IOException 
	 */
	public static void main ( String[] args ) throws IOException, InterruptedException
	{
		JSONObject item = new JSONObject ( );
		if ( args.length == 0 )
		{
			System.err.println ( "Runtime execute args.. execute message.." );
			System.exit ( 0 );
		}
		String command = "";
		for ( int i = 0 ; i < args.length ; i++ )
		{
			command += " " + args[i];
		}

		try
		{
			System.out.println ( getRuntime ( command ) );
		}
		catch ( XCNException e )
		{
			item.put ( "success", "fail" );
			item.put ( "message", e.getMessage ( ) );
		}
		catch ( Exception e )
		{
			item.put ( "success", "fail" );
			item.put ( "message", "서버 에러가 ....." );
		}
		System.out.println ( item );
	}
	
}
